<!DOCTYPE html>
<html lang="en">
<title>订单管理--训练营课程订单</title>
<#import "/layout/layout.html" as body/>
<@body.page>

<style>
    a {
        color: #666;
    }
    .tcdPageCode {
        padding: 15px 20px;
        text-align: left;
        color: #ccc;
    }
    .tcdPageCode a {
        display: inline-block;
        color: #428bca;
        height: 25px;
        line-height: 25px;
        padding: 0 10px;
        border: 1px solid #ddd;
        margin: 0 2px;
        border-radius: 4px;
        vertical-align: middle;
    }
    .tcdPageCode a:hover {
        text-decoration: none;
        border: 1px solid #428bca;
    }
    .tcdPageCode span.current {
        display: inline-block;
        height: 25px;
        line-height: 25px;
        padding: 0 10px;
        margin: 0 2px;
        color: #fff;
        background-color: #428bca;
        border: 1px solid #428bca;
        border-radius: 4px;
        vertical-align: middle;
    }
    .tcdPageCode span.disabled {
        display: inline-block;
        height: 25px;
        line-height: 25px;
        padding: 0 10px;
        margin: 0 2px;
        color: #bfbfbf;
        background: #f2f2f2;
        border: 1px solid #bfbfbf;
        border-radius: 4px;
        vertical-align: middle;
    }
    .chosen-container {
        min-width: 160px !important;
    }
    .modal-loading { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 10000; background: rgba(0, 0, 0, .5) url("${baseUrl}img/loading.gif") no-repeat center; }
</style>
<div class="modal-loading"></div>

<div class="wrapper wrapper-content animated fadeIn">
    <div class="row">
        <div class="col-lg-12 margin-top">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5 class="pull-left">训练营课程订单</h5>
                    <!--<button type="button" class="btn btn-primary btn-sm pull-right">导出表格</button>-->
                </div>
                <div class="ibox-content">

                    <ul class="nav navbar-nav status-nav" id="myType">
                        <li class="active"><a href="#">已支付▪成营</a></li>
                        <li><a href="#">已支付▪成营排队中</a></li>
                        <li><a href="#">已支付▪未成营</a></li>
                        <li><a href="#">已结束</a></li>
                        <li><a href="#">待支付</a></li>
                        <li><a href="#">被动取消</a></li>
                        <li><a href="#">主动取消</a></li>
                        <li><a href="#">已退款</a></li>
                    </ul>
                    <div class="wrapper wrapper-content animated fadeInRight">
                        <div class="row">
                            <div class="col-lg-12">
                                <div class="ibox-content">
                                    <form class="form-inline" role="form">
                                        <div class="form-group margin-left">
                                            <label for="daterange1">订单号：</label>
                                            <input class="form-control" id="my_tradeId" type="text" placeholder="订单号"/>
                                        </div>
                                        <div class="form-group date-rangepicker">
                                            <label for="daterange">日期：</label>
                                            <input class="form-control" id="my_time" type="text" placeholder="时间" name="daterange" value="" style="width: 188px"/>
                                        </div>
                                        <div class="form-group margin-left">
                                            <label for="daterange1">课程：</label>
                                            <input class="form-control" type="text" id="my_course" style="width:120px" placeholder="请输入课程ID"/>
                                        </div>
                                        <div class="form-group margin-left">
                                            <label for="daterange2">手机号码：</label>
                                            <input class="form-control" type="text" id="my_mobile" style="width:150px" placeholder="请输入用户手机号"/>
                                        </div>
                                        <div class="form-group margin-left">
                                            <label for="daterange2">用户ID：</label>
                                            <input class="form-control" id="my_userId" name="my_userId" type="text" style="width:150px" placeholder="用户ID"/>
                                        </div>
                                        <div class="form-group margin-left">
                                            <label for="daterange2">用户昵称：</label>
                                            <input class="form-control" id="my_userName" name="my_userName" type="text" style="width:150px" placeholder="用户昵称"/>
                                        </div>
                                        <div class="form-group margin-left">
                                            <label>门店：</label>
                                        </div>
                                        <div class="form-group margin-left">
                                            <select data-placeholder="请输入门店" id="my_store_list" class="chosen-select store_list" style="width:100%;" tabindex="2">
                                            </select>
                                        </div>
                                        <button type="button" id="btn_my_selects" class="btn btn-outline btn-primary">确认</button>
                                        <!-- <div class="form-group margin-right" style="">
                                            <button type="button" class="btn btn-outline excelButton"
                                                    style="margin-top: 5px" id="my_export" onclick="tkExport(3)">导出</button>
                                        </div> -->
                                    </form>
                                    <hr>
                                    <div class="table-responsive">
                                        <!-- dataTables-example -->
                                        <table class="table table-hover table-center dataTables-example">
                                            <thead>
                                            <tr>
                                                <th>序号</th>
                                                <th>交易编号</th>
                                                <th>下订单时间</th>
                                                <th>订单号</th>
                                                <th>课程名称</th>
                                                <th>开始时间</th>
                                                <th>用户</th>
                                                <th>身份</th>
                                                <th>费用</th>
                                                <th>优惠券</th>
                                                <th>购买人数</th>
                                                <th>实付</th>
                                                <th>门店</th>
                                                <th>操作</th>
                                            </tr>
                                            </thead>
                                            <!-- 页面加载的数据  -->
                                            <tbody id="td3">
                                            </tfoot>
                                        </table>
                                    </div>
                                </div>
                                <div class="ibox-footer overflow">
                                    <h4 class="pull-left margin-left" id="my_tongji" style="color: #2fb146">订单合计：0笔</h4>
                                    <h4 class="pull-left margin-left" id="my_feiyong" style="color: #2fb146">费用合计：¥0</h4>
                                    <h4 class="pull-left" id="my_shifu" style="color: #2fb146">实付合计：¥0</h4>
                                    <div class="pull-right copot-page" id="my_page_list"></div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

<!-- mode start -->
<input type="hidden" id="click_order_type" value="团体课程">
<input type="hidden" id="order_type_child" value="1">
<input type="hidden" id="orderStatus" name="orderStatus" value="1">
<input type="hidden" id="baseUrl" value="${baseUrl}">
<input type="hidden" id="pageNum" name="pageNum" value="1">
<!-- mode end  -->
<link href="${baseUrl}css/plugins/clockpicker/clockpicker.css" rel="stylesheet">
<script src="${baseUrl}js/plugins/clockpicker/clockpicker.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-modal/2.2.6/js/bootstrap-modal.js"></script>
<script>
    /*function fnClickAddRow() {
     $('#editable').dataTable().fnAddData(["Custom row", "New row", "New row", "New row", "New row"]);
     }*/
    $(document).ready(function () {

        //时间选择
        $('input[name="daterange"]').daterangepicker({
            startDate: moment().startOf('day'),
            endDate: moment(),
            //minDate: '01/01/2012',    //最小时间
            //maxDate: moment(), //最大时间
            dateLimit: {days: 365}, //起止时间的最大间隔
            showDropdowns: true,
            showWeekNumbers: false, //是否显示第几周
            timePicker: false, //是否显示小时和分钟
            timePickerIncrement: 60, //时间的增量，单位为分钟
            timePicker12Hour: false, //是否使用12小时制来显示时间
            ranges: {
                //'最近1小时': [moment().subtract('hours',1), moment()],
                '今日': [moment().startOf('day'), moment()],
                '昨日': [moment().subtract('days', 1).startOf('day'), moment().subtract('days', 1).endOf('day')],
                '最近7日': [moment().subtract('days', 6), moment()],
                '最近30日': [moment().subtract('days', 30), moment()]
            },
            opens: 'right', //日期选择框的弹出位置
            buttonClasses: ['btn btn-default'],
            applyClass: 'btn-small btn-primary blue',
            cancelClass: 'btn-small',
            format: 'YYYY-MM-DD', //控件中from和to 显示的日期格式 YYYY-MM-DD HH:mm:ss
            separator: '~',
            locale: {
                applyLabel: '确定',
                cancelLabel: '取消',
                fromLabel: '起始时间',
                toLabel: '结束时间',
                customRangeLabel: '自定义',
                daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                    '七月', '八月', '九月', '十月', '十一月', '十二月'],
                firstDay: 1
            }
        }, function (start, end, label) {//格式化日期显示框
            $('.date-rangepicker span').html(start.format('YYYY-MM-DD HH:mm:ss') + ' - ' + end.format('YYYY-MM-DD HH:mm:ss'));
        });
		
        // 日期类扩展
        Date.prototype.pattern = function (fmt) {
            var o = {
                "M+": this.getMonth() + 1, // 月份
                "d+": this.getDate(), // 日
                "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, // 小时
                "H+": this.getHours(), // 小时
                "m+": this.getMinutes(), // 分
                "s+": this.getSeconds(), // 秒
                "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
                "S": this.getMilliseconds() // 毫秒
            };
            var week = {
                "0": "/u65e5",
                "1": "/u4e00",
                "2": "/u4e8c",
                "3": "/u4e09",
                "4": "/u56db",
                "5": "/u4e94",
                "6": "/u516d"
            };
            if (/(y+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            if (/(E+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                }
            }
            var str = fmt.lastIndexOf("N");
            if (str != -1) {
                return "";
            }

            return fmt;
        }
        
        
        // 初始化
        init();
     	// 训练营订单类型被点击的时候
        $("#myType li a").click(function () {
            $('#myType li').removeClass('active');
            $(this).parent().addClass('active');
            $(this).context.innerHTML;
            var ordetStatusType = $(this).context.innerHTML;
            getOrderStatus(ordetStatusType);
            getFunCampHtml();
        });
     	
     	// 查询订单
     	$("#btn_my_selects").click(function(){
     		getFunCampHtml();
     	});
    });
	
     // 初始化函数
     function init(){
    	coachList();
     	stortList();
     	// 初始化数据
     	getFunCampHtml();
     }
     // 获取数据展示
     
	
	function getFunCampHtml() {
		$('.modal-loading').show();
		// 异步请求数据
		var url = "get_fun_camp_order_list";
		var param = getParam();
		$("#my_tongji").html("订单合计：" + 0 + "笔");
		$("#my_feiyong").html("费用合计：¥" + 0 + "&nbsp;元");
		$("#my_shifu").html("&nbsp;&nbsp;实付合计：¥" + 0 + "&nbsp;元");
		getFunCampOrderListJsonToAjax(url, param, setFunCampHtml);
		

	}
	// 渲染页面
	function setFunCampHtml(date) {
		var param = getParam();
		var type = param.type;
		
		// 训练营
		var dataL = date.data.MyData;
		if (date.ret == '-1') {
			swal("获取数据失败", "请联系管理员处理", "error");
			return;
		}
		var trtd = "";
		$('#td3').empty();
		for (var i = 0; i < dataL.length; i++) {
			var datas = dataL[i];
			var tds = "";
			var trs = '</tr>';
			var pay_type = '';
			if (datas.pay_type == 3) {
				pay_type = '(企)';
			} else if (datas.pay_type == 2) {
				pay_type = '(储)';
			} else if (datas.pay_type == 1) {
				pay_type = '(微)';
			} else if (datas.pay_type == 4) {
				pay_type = "(" + datas.weixinAmt + '_微/' + datas.consumeAmt + "_储)";
			} else if (datas.pay_type == 5) {
				pay_type = "(" + datas.weixinAmt + '_微/' + datas.companyAmt + "_企)";
			}
			
			// 根据订单状态类型判断是否需要退款或者是取消订单
			var buttonType = '<button type="button" class="btn btn-default btn-sm" {cancelOrder}>'
	            + '<span class="glyphicon glyphicon-ban-circle"></span>{title}</button>';
	        // 已支付的订单需要取消
			if(type == 1 || type == 2 || type == 9){
				buttonType = buttonType.replace('{cancelOrder}','onclick="cancelOrder('+datas.order_id+')"');
            	buttonType = buttonType.replace("{title}","取消");
			}else if(type == 7 && datas.cancel_backmoney == "1" && datas.price1 > 0 
					|| type == 7 && datas.cancel_backmoney == 1 && datas.price1 > 0 ){
				// 主动取消需要判断是否可退款 这里还需要判断是否可以退款的
            	buttonType = buttonType.replace('{cancelOrder}','onclick="refundOrder('+datas.order_id+')"');
            	buttonType = buttonType.replace("{title}","退款");
			}else if(type == 5  && datas.price1 > 0 
					|| type == 5 && datas.price1 > 0 ){
				// 被动取消只有金额大于0 的订单才可以退款 这里还需要判断是否可以退款的
            	buttonType = buttonType.replace('{cancelOrder}','onclick="refundOrder('+datas.order_id+')"');
            	buttonType = buttonType.replace("{title}","退款");
			}else{
				buttonType = "";
			}
			
			trtd = trtd
					+ '<tr>'
					+ '<td>' + (i + 1)+ '</td>'
					+ '<td>' + datas.trade_id + '</td>'
					+ '<td>' + getDateByTypeMY(type, datas.created_time,datas.cancel_time, datas.refund_time) + '</td>'
					+ '<td>' + datas.order_number + '</td>' 
					+ '<td>' + datas.title + '</td>' 
					+ '<td>' + new Date(datas.start_time).pattern("yyyy-MM-dd HH:mm:ss") + '</td>' 
					+ '<td>' + datas.nick_name + '</br>' + (datas.mobile == null ? "" : datas.mobile) + '</td>'
					+ '<td>' + datas.level + '</td>' 
					+ '<td>' + datas.prime_price + '</td>' 
					+ '<td>' + (datas.cash_money == undefined ? "" : datas.cash_money)+ '</td>'
					+ '<td>' + datas.person_count + '</td>' 
					+ '<td>' + datas.price1 + pay_type + '</td>' 
					+ '<td>' + datas.store_name + '</td>'
					+ '<td>' + buttonType + '</td>'
					+'</tr>'
					;
			
			//trtd = trtd + tds + trs;
		}
		$('#td3').append(trtd);
		$("#my_tongji").html("订单合计：" + date.data.pageCount + "笔");
		$("#my_feiyong").html("费用合计：¥" + date.data.totalFee + "&nbsp;元");
		$("#my_shifu").html("&nbsp;&nbsp;实付合计：¥" + date.data.totalPayment + "&nbsp;元");
		setPageHtml(date.data.pageNum, date.data.pageCount);
		$('.modal-loading').hide();
	}

	// 异步请求数据
	function getFunCampOrderListJsonToAjax(url, param, callBack) {
		$.ajax({
			url : url,//
			data : param,
			type : 'post',
			cache : false,
			dataType : 'json',
			success : function(data) {
				if (data.ret == 0) {
					setFunCampHtml(data);
				}
			},
			error : function() {
				alert("页面数据加载失败！");
			}
		});
	}

	// 获取参数
	function getParam() {
		var courseTime = $("#my_time").val();
        var courseTimeStr = courseTime.split("~");
        var c_start_time = courseTimeStr[0];
        var c_end_time = courseTimeStr[1];
        
		var param = {
			"course_stime" 	: c_start_time,
			"course_etime" 	: c_end_time,
			"course_id" 	: $("#my_course").val(),
			"mobile" 		: $("#my_mobile").val(),
			"store_id" 		: $("#my_store_list").val(),
			"type" 			: $("#orderStatus").val(),
			"tradeId" 		: $("#my_tradeId").val(),
			"pageNum" 		: $("#pageNum").val(),
			"userName"		: $("#my_userName").val()
		}
		return param;
	}

	// 给参数赋值
	function setParam(param) {

	}

	// 设置分页组件
	function setPageHtml(pageNo, pageCount) {
		new Page({
            parent: $("#my_page_list"),
            nowPage: pageNo,// 第几页
            pageSize: 20,// 每页条数
            totalCount: pageCount,// 总共有几条
            setting: {
                defaultPage: 7,// 默认显示可点击分页的个数Math.floor(data.data.pageCount / 10)
                firstPageText: "首页",
                prevPageText: "上一页",
                nextPageText: "下一页",
                lastPageText: "尾页"
            },
            callback: function (nowPage, totalPage) {
                $("#pageNum").val(nowPage);
                getFunCampHtml();
            }
        });
	}
	
	// 训练营课程 
    function getOrderStatus(type) {
        if (type == "已支付▪成营" || type == '<a href="#">已支付▪成营</a>') {
        	$("#orderStatus").val(1);
        }
        if (type == "已支付▪未成营" || type == '<a href="#">已支付▪未成营</a>') {
        	$("#orderStatus").val(2);
        }
        if (type == "已结束" || type == '<a href="#">已结束</a>') {
        	$("#orderStatus").val(3);
        }
        if (type == "待支付" || type == '<a href="#">待支付</a>') {
        	$("#orderStatus").val(4);
        }
        if (type == "被动取消" || type == '<a href="#">被动取消</a>') {
        	$("#orderStatus").val(5);
        }
        if (type == "已退款" || type == '<a href="#">已退款</a>') {
        	$("#orderStatus").val(6);
        }
        if (type == "主动取消" || type == '<a href="#">主动取消</a>') {
        	$("#orderStatus").val(7);
        }
        if (type == "已支付▪成营排队中" || type == '<a href="#">已支付▪成营排队中</a>') {
        	$("#orderStatus").val(9);
        }
    }
	
 // 加载门店列表
    function stortList() {
        // 门店
        $.ajax({
            url: 'getStoreList.action',//
            data: "",
            type: 'post',
            cache: false,
            dataType: 'json',
            success: function (data) {
                var dataL = data.data;
                var bool = data.ret;
                var list = '';
                $("store_list").empty();
                var options = '<option value="0">全部</option>';
                if (bool == 0 || bool == '0') {
                    for (var i = 0; i < dataL.length; i++) {
                        var datas = dataL[i];
                        options = options + '<option value="'
                            + datas.code + '">'
                            + datas.name + '</option>';
                    }

                }
                $(".store_list").append(options);
                $(".store_list").trigger("chosen:updated");
                $(".store_list").trigger("liszt:updated");
                $(".store_list").chosen();
            },
            error: function () {
                alert("页面数据加载失败！");
            }
        });
    }
    
    // 加载教练列表
    function coachList() {
        $.ajax({
            url: 'get_coach_list',//
            data: "",
            type: 'post',
            cache: false,
            dataType: 'json',
            success: function (data) {
                var dataL = data.data;
                var bool = data.ret;
                var list = '';
                $(".coach_list").empty();
                var options = '<option value="0">全部</option>';
                if (bool == 0 || bool == '0') {
                    for (var i = 0; i < dataL.length; i++) {
                        var datas = dataL[i];
                        options = options + '<option value="'
                            + datas.id + '">'
                            + datas.nickName + '</option>';
                    }

                }
                $(".coach_list").append(options);
                $(".coach_list").trigger("chosen:updated");
                $(".coach_list").chosen();

            },
            error: function () {
                alert("页面数据加载失败！");
            }
        });
    }
    
    function updateOrder(order,type){
    	if(type == 1){
    		cancelOrder(orderId);
    	}else{
    		refundOrder(orderId);
    	}
    }
    
 	// 订单取消函数
    function cancelOrder(orderId) {
    	swal({
            title: "确定取消订单?" + orderId,
            text: "取消订单会退到被动取消里!",
            type: "warning",
            showCancelButton: true,
            cancelButtonText: "容我三思！",
            confirmButtonText: "确定!",
        }).then(function () {
            $.ajax({
                url: "updateOrder",              // 请求地址
                data: {
                    "orderId": orderId,
                    "type": 1
                },
                type: 'post',
                cache: false,
                dataType: 'json',
                success: function (data) {
                    // 刷新页面，不刷新整体页面只是刷新table
                    if(data.ret == 0){
                    	swal("保存成功!", "页面即将重新加载,请稍后...", "success");
                        window.setTimeout(function () {
                        	getFunCampHtml();
                        }, 1000);
                    }else{
                    	swal("取消失败!", "请联系管理员处理", "error");
                    }
                    
                },
                error: function () {
                    swal("取消失败!", "请联系管理员处理", "error");
                }
            });

        }, function () {
		});
    }
    
    // 私教在管理后台点击退款的提示文案：
	// 请与教练确认该订单当前的销课数是否为实际上课数量，避免未及时销课的课时被退款的情况发生
    // 退款函数
    function refundOrder(orderId){
    	swal({
            title: "确定退款" + orderId,
            text: "退款之后金额直接打入对方账户!",
            type: "warning",
            showCancelButton: true,
            cancelButtonText: "容我三思！",
            confirmButtonText: "确定!",
        }).then(function () {
            $.ajax({
                url: "createdRefun.action",              // 请求地址
                data: {
                    "orderId": orderId,
                    "biaoshi": 1
                },
                type: 'post',
                cache: false,
                dataType: 'json',
                success: function (data) {
                	if(data.ret == 0){
                		swal("退款成功!", "您已退款成功,金额已打入对方账户", "success");
                        window.setTimeout(function () {
                        	getFunCampHtml();
                        }, 1000);
                	}else{
                		swal("退款失败!", data.msg, "error");
                	}
                    
                },
                error: function () {
                    swal("退款失败!", "系统运行异常，请联系管理员处理", "error");
                }
            });

        }, function () {
    	});
    }
    
    // 获取已取消订单展示类型
    function getDateByTypeMY(type, time1, time2, time3) {
        var time = '';
        if (type == 5 || type == 7) {
            time = new Date(time1).pattern("yyyy-MM-dd HH:mm:ss") + '(下单)</br>' + new Date(time2).pattern("yyyy-MM-dd HH:mm:ss") + '(取消)';

        } else if (type == 6) {
            time = new Date(time1).pattern("yyyy-MM-dd HH:mm:ss") + '(下单)</br>' + new Date(time3).pattern("yyyy-MM-dd HH:mm:ss") + '(退款)';
        } else {
            time = new Date(time1).pattern("yyyy-MM-dd HH:mm:ss");
        }
        return time;
    }
</script>

</@body.page>
</html>